package com.example.yyang.demo.adapter

import android.content.Context
import android.support.v7.widget.RecyclerView
import android.text.Layout
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.example.yyang.demo.R
import com.example.yyang.demo.model.News
import kotlinx.android.synthetic.main.list_news.view.*
import java.security.AccessControlContext

class NewsAdapter : RecyclerView.Adapter
<NewsAdapter.ViewHolder>{
    private var context: Context? = null
    private var newsList: ArrayList<News>? = null


    constructor(context: Context,newsList: ArrayList<News>){
        this.context = context
        this.newsList = newsList
    }
    class ViewHolder : RecyclerView.ViewHolder {
        var ivDes: ImageView
        var tvTitle: TextView
        constructor(itemView: View):super(itemView){
            ivDes = itemView.findViewById(R.id.iv_news_des)
            tvTitle = itemView.findViewById(R.id.tv_news_title)
        }
    }

    override fun onBindViewHolder(p0: ViewHolder, p1: Int) {
        if (newsList?.size as Int > p1){
            val news = newsList?.get(p1)
            //使用Glide加载图片
            Glide.with(context).load(news?.thumbnailPicS).into(p0.ivDes)
            //设置标题
            p0.tvTitle.text=news?.title
        }
    }

    override fun getItemCount(): Int {
        return newsList?.size as Int
    }

    override fun onCreateViewHolder(p0: ViewGroup, p1: Int): ViewHolder {
        val view = LayoutInflater.from(context).inflate(R.layout.list_news,p0,false)
        return ViewHolder(view)
    }

    fun addData(dataList:ArrayList<News>):Unit{
        if (dataList.size == 0){
            return
        }
        newsList?.addAll(dataList)
        notifyDataSetChanged()
    }

    fun updateData(dataList: ArrayList<News>):Unit{
        if (dataList.size == 0){
            return
        }
        newsList?.clear()
        newsList?.addAll(dataList)
        notifyDataSetChanged()
    }
}